package service;

import mapper.BrandMapper;
import pojo.Brand;
import utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;

public class BrandService {

    //品牌查询
    public List<Brand> selectAll(){
        //1.开启会话
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        //2.获取Mapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行查询
        List<Brand> brands = mapper.selectAll();
        //4.关闭
        sqlSession.close();
        //5.返回数据
        return brands;
    }
    //    品牌新增
    public void add(Brand brand){
        //1.开启会话
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        //2.获取Mapper
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //3.换行查询
        brandMapper.add(brand);
        //4.提交事务
        sqlSession.commit();
        //5.关闭
        sqlSession.close();
    }




    //单个查询
    public Brand selectById(int id){
        //1.开启会话
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        //2.获取Mapper
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //3.执行查询
        Brand brand = brandMapper.selectById(id);
        //4.关闭
        sqlSession.close();
        //5.返回数据
        return brand;
    }


    //    品牌修改

    public void update(Brand brand){
        //1.开启会话
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        //2.获取Mapper
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //3.换行查询
        brandMapper.update(brand);
        //4.提交事务
        sqlSession.commit();
        //5.关闭
        sqlSession.close();
    }

    //品牌删除
    public void delete(int id){
        //1.开启会话
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = factory.openSession();
        //2.获取Mapper
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        //3.换行查询
        brandMapper.deleteById(id);
        //4.提交事务
        sqlSession.commit();
        //5.关闭
        sqlSession.close();
    }
}